/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Golf_Manager;

import Golf_Manager.editor.doc.TextLimitDocument;
import Golf_Manager.print.PrintPreview;
import Golf_Manager.sqlite.JoinMemberDAO;
import Golf_Manager.vo.Group;
import Golf_Manager.vo.JoinMember;
import Golf_Manager.renderer.ColorColumnRenderer;
import Golf_Manager.sqlite.GroupDAO;
import Golf_Manager.util.Util;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.im.InputContext;
import java.awt.im.InputSubset;
import static java.awt.image.ImageObserver.WIDTH;
import java.awt.print.PrinterJob;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.OrientationRequested;
import javax.print.attribute.standard.Sides;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author Administrator
 */
public class GroupMakeFrame extends javax.swing.JInternalFrame {

    /**
     * Creates new form GroupMakeFrame
     */
    public GroupMakeFrame() {
        initComponents();
        
        //joinMemberTable 설정 시작
        
        joinMemberTable.getColumnModel().getColumn(0).setPreferredWidth(50);
        joinMemberTable.getColumnModel().getColumn(1).setCellRenderer(new ColorColumnRenderer("joinMemberTable"));
        joinMemberTable.getColumnModel().getColumn(1).setPreferredWidth(50);
        joinMemberTable.getColumnModel().getColumn(2).setPreferredWidth(80);
        joinMemberTable.getColumnModel().getColumn(3).setPreferredWidth(70);
        joinMemberTable.getColumnModel().getColumn(4).setPreferredWidth(100);
        //joinMemberTable 설정 종료
        
        //groupTable설정 시작
        //CELL 0설정 시작
        JTextField jfGroupField = new JTextField();
        jfGroupField.setHorizontalAlignment(JTextField.CENTER);
        jfGroupField.setDocument(new TextLimitDocument(7));
        jfGroupField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                super.focusGained(e); //To change body of generated methods, choose Tools | Templates.
                JTextField eventJfName = (JTextField)e.getSource();
                InputContext icx  = eventJfName.getInputContext();
                if(icx != null)
                    eventJfName.getInputContext().setCharacterSubsets(new Character.Subset[]{InputSubset.HANJA });
            }

            @Override
            public void focusLost(FocusEvent e) {
                super.focusLost(e); //To change body of generated methods, choose Tools | Templates.
                 groupTable.getColumnModel().getColumn(0).getCellEditor().stopCellEditing();
            }
            
            
        });
        groupTable.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(jfGroupField));
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setHorizontalAlignment(JTextField.CENTER);
        groupTable.getColumnModel().getColumn(0).setCellRenderer(renderer);
        groupTable.getColumnModel().getColumn(0).setPreferredWidth(50);
        //CELL 0설정 끝
        
        groupTable.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(jfGroupField));
        groupTable.getColumnModel().getColumn(1).setCellRenderer(renderer);
        
        ColorColumnRenderer colorColumnRenderer = new ColorColumnRenderer("groupTable");
        colorColumnRenderer.setHorizontalAlignment(JTextField.CENTER);
        
        groupTable.getColumnModel().getColumn(2).setCellRenderer(colorColumnRenderer);
        groupTable.getColumnModel().getColumn(3).setCellRenderer(colorColumnRenderer);
        groupTable.getColumnModel().getColumn(4).setCellRenderer(colorColumnRenderer);
        //groupTable설정 설정 종료
        
        searchJoinMembers("","");
        createGroups();
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        joinMemberTable = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        groupTable = new javax.swing.JTable();
        jBtnAdd = new javax.swing.JButton();
        jBtnDel = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        searchResult = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel4 = new javax.swing.JLabel();
        jComboSelectKey = new javax.swing.JComboBox();
        jComboOrder = new javax.swing.JComboBox();
        jBtnGroupMake = new javax.swing.JButton();
        jBtnSave = new javax.swing.JButton();
        jBtnPrint = new javax.swing.JButton();
        jDateGroupDate = new com.toedter.calendar.JDateChooser();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jChecRecordCheck = new javax.swing.JCheckBox();

        setTitle("조편성");
        setName(""); // NOI18N
        setPreferredSize(new java.awt.Dimension(1024, 768));
        setVisible(true);

        joinMemberTable.setModel(new Golf_Manager.model.JoinMemberModel());
        joinMemberTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        joinMemberTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        joinMemberTable.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(joinMemberTable);

        groupTable.setModel(new Golf_Manager.model.GroupModel());
        groupTable.setCellSelectionEnabled(true);
        groupTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        groupTable.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(groupTable);

        jBtnAdd.setText("▶");
        jBtnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnAddActionPerformed(evt);
            }
        });

        jBtnDel.setText("◀");
        jBtnDel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnDelActionPerformed(evt);
            }
        });

        jLabel1.setText("참여인원 :");

        searchResult.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        searchResult.setText("0 명");

        jLabel2.setText("대상자 목록");

        jLabel3.setText("편성조");

        jLabel4.setText("조편성일자");

        jComboSelectKey.setMaximumRowCount(11);
        jComboSelectKey.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "선택", "이름", "생년월일", "회사명", "핸디", "비고1", "비고2", "비고3", "전월 성적순", "랜덤" }));
        //jComboselectKey.addItemListener(new ItemChangeListener());
        jComboSelectKey.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboSelectKeyItemStateChanged(evt);
            }
        });

        jComboOrder.setMaximumRowCount(3);
        jComboOrder.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "선택" }));
        jComboOrder.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboOrderItemStateChanged(evt);
            }
        });
        //jComboOrder.addItemListener(new ItemChangeListener());

        jBtnGroupMake.setText("조편성");
        jBtnGroupMake.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnGroupMakeActionPerformed(evt);
            }
        });

        jBtnSave.setText("저장");
        jBtnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnSaveActionPerformed(evt);
            }
        });

        jBtnPrint.setText("출력");
        jBtnPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnPrintActionPerformed(evt);
            }
        });
        jBtnPrint.setEnabled(false);

        jDateGroupDate.setDateFormatString("yyyy-MM-dd");

        jLabel5.setText("편성기준 필드 선택");

        jLabel6.setText("정렬기준");

        jChecRecordCheck.setText("최근전적반영");
        jChecRecordCheck.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator2)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jComboSelectKey, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jChecRecordCheck)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBtnGroupMake)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jBtnSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBtnPrint))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jBtnDel)
                                    .addComponent(jBtnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(searchResult, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(309, 309, 309)
                                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jDateGroupDate, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE))
                            .addComponent(jScrollPane2))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jBtnGroupMake, jBtnPrint, jBtnSave});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jBtnAdd, jBtnDel});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(44, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboSelectKey, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)
                    .addComponent(jComboOrder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtnGroupMake, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jChecRecordCheck)
                    .addComponent(jBtnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtnPrint))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 11, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchResult, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jDateGroupDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE)
                        .addComponent(jScrollPane2))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(198, 198, 198)
                        .addComponent(jBtnAdd)
                        .addGap(18, 18, 18)
                        .addComponent(jBtnDel)))
                .addGap(31, 31, 31))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jBtnGroupMake, jBtnPrint, jBtnSave, jComboOrder, jComboSelectKey, jDateGroupDate});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBtnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnAddActionPerformed
        // TODO add your handling code here:
        if(jComboSelectKey.getSelectedIndex() > 0){
            if(jComboSelectKey.getSelectedIndex() < 8 && jComboOrder.getSelectedIndex() > 0){
                addJoinmember();
            } else if(jComboSelectKey.getSelectedIndex() > 7){
                addJoinmember();
            } else {
                JOptionPane.showMessageDialog(rootPane, "정렬 기준을 선택해 주세요.", "확인", WIDTH);
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "편성기준 필드를 선택해 주세요", "확인", WIDTH);
        }
    }//GEN-LAST:event_jBtnAddActionPerformed
    private void addJoinmember(){
        
        Golf_Manager.model.JoinMemberModel joinMemberModel =  (Golf_Manager.model.JoinMemberModel)joinMemberTable.getModel();
        Golf_Manager.model.GroupModel groupModel =  (Golf_Manager.model.GroupModel)groupTable.getModel();

        int addJoinMemberRow = joinMemberModel.getCheckRow();
        int selGroupRow =  groupTable.getSelectedRow();
        int selGroupCol = groupTable.getSelectedColumn();

        //System.out.println("addJoinMemberRow :" + addJoinMemberRow + ", selGroupRow : " + selGroupRow + ", selGroupCol : " + selGroupCol);

        if(addJoinMemberRow < 0){
            JOptionPane.showMessageDialog(rootPane, "추가 하고자 하는 회원을 선택하십시오.", "확인", WIDTH);
        } else if(selGroupRow < 0 || selGroupCol < 1) {
            JOptionPane.showMessageDialog(rootPane, "추가 하고자 하는 조를 선택하십시오.", "확인", WIDTH);
        } else {
            JoinMember joinMember = joinMemberModel.getJoinMember(addJoinMemberRow);
            Group group = groupModel.getGroup(selGroupRow); //현재 그룹 데이터
            String alertMsg = "";

            if(group.getGroupMemberCnt() == 1 && (selGroupCol == 2 || selGroupCol == 3 || selGroupCol == 4)){
                switch(selGroupCol){
                    case 2: alertMsg = "조원이 1명인 조입니다. 조원2에 입력하실 수 없습니다."; break;
                    case 3: alertMsg = "조원이 1명인 조입니다. 조원3에 입력하실 수 없습니다."; break;
                    case 4: alertMsg = "조원이 1명인 조입니다. 조원4에 입력하실 수 없습니다."; break;    
                } 
                JOptionPane.showMessageDialog(rootPane, alertMsg, "확인", WIDTH);
            } else if(group.getGroupMemberCnt() == 2 && (selGroupCol == 3 || selGroupCol == 4)){
                switch(selGroupCol){
                    case 3: alertMsg = "조원이 2명인 조입니다. 조원3에 입력하실 수 없습니다."; break;
                    case 4: alertMsg = "조원이 2명인 조입니다. 조원4에 입력하실 수 없습니다."; break;    
                } 
                JOptionPane.showMessageDialog(rootPane, alertMsg, "확인", WIDTH);
            } else if(group.getGroupMemberCnt() == 3 && selGroupCol == 4){
                JOptionPane.showMessageDialog(rootPane, "조원이 3명인 조입니다. 조원4에 입력하실 수 없습니다.", "확인", WIDTH);
            } else {
                //이전데이터 삭제
                int oldJoinMemberRow = groupModel.getMemberRow(selGroupRow, selGroupCol);
                //System.out.println(oldJoinMemberRow);
                groupModel.setGroupMember(joinMember.getGroupRow(), joinMember.getGroupCol(), -1, "", "");
                if(oldJoinMemberRow > -1)
                    joinMemberModel.setGroupData(oldJoinMemberRow, "", -1, -1);

                //현재 데이터 설정
                joinMemberModel.setGroupData(addJoinMemberRow, group.getGroupName(), selGroupRow, selGroupCol);
                groupModel.setGroupMember(selGroupRow, selGroupCol, addJoinMemberRow, joinMember.getMemberSeq(), joinMember.getName()/* + "(" + joinMember.getBirth() + ")"*/);
                joinMemberModel.setCheckRow(-1);
                joinMemberModel.setCheckValue(false);

                joinMemberTable.repaint();
                groupTable.repaint();
            }
        }
    }
    private void jBtnDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnDelActionPerformed
        // TODO add your handling code here:
        if(jComboSelectKey.getSelectedIndex() > 0) {
            if(jComboSelectKey.getSelectedIndex() < 8 && jComboOrder.getSelectedIndex() > 0){
                delJoinmember();
            } else if(jComboSelectKey.getSelectedIndex() > 7){
                delJoinmember();
            } else {
                JOptionPane.showMessageDialog(rootPane, "정렬 기준을 선택해 주세요.", "확인", WIDTH);
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "편성기준 필드를 선택해 주세요", "확인", WIDTH);
        }
    }//GEN-LAST:event_jBtnDelActionPerformed
    private void delJoinmember(){
        Golf_Manager.model.JoinMemberModel joinMemberModel =  (Golf_Manager.model.JoinMemberModel)joinMemberTable.getModel();
        Golf_Manager.model.GroupModel groupModel =  (Golf_Manager.model.GroupModel)groupTable.getModel();
        int selGroupRow =  groupTable.getSelectedRow();
        int selGroupCol = groupTable.getSelectedColumn();

        if(selGroupRow < 0 || selGroupCol < 1) {
            JOptionPane.showMessageDialog(rootPane, "삭제 하고자 하는 조를 선택하십시오.", "확인", WIDTH);
        } else {
            Group group = groupModel.getGroup(selGroupRow);

            int joinMemberRow = -1;

            switch(selGroupCol){
                case 1: joinMemberRow = group.getMemberRow1(); break;
                case 2: joinMemberRow = group.getMemberRow2(); break;
                case 3: joinMemberRow = group.getMemberRow3(); break;
                case 4: joinMemberRow = group.getMemberRow4(); break;
            }
            if(joinMemberRow > -1){
                joinMemberModel.setGroupData(joinMemberRow, "", -1, -1);
                groupModel.setGroupMember(selGroupRow, selGroupCol, -1, "", "");
                joinMemberTable.repaint();
                groupTable.repaint();
            } else {
                JOptionPane.showMessageDialog(rootPane, "삭제 하고자 하는 조원이 없습니다.", "확인", WIDTH);
            }   
        }
    }
    private void jComboOrderItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboOrderItemStateChanged
        // TODO add your handling code here:
        if(evt.getStateChange() == 1){
            JComboBox jComboBox = (JComboBox)evt.getSource();
            if(jComboBox.getSelectedIndex() > 0){
                //System.out.println(evt);  
                //System.out.println(jComboBox.getSelectedItem());  
                
                String selectKey = ""; 
                String orderString = "";
                String order = jComboBox.getSelectedIndex() == 1 ? "ASC" : "DESC";
                if(jComboSelectKey.getSelectedIndex() > 0){
                    
                    TableColumnModel cmodel = joinMemberTable.getColumnModel();
                    
                    switch(jComboSelectKey.getSelectedIndex()){
                        case 1: orderString = "NAME " + order; break;
                        case 2: orderString = "BIRTH " + order; break;
                        case 3: cmodel.getColumn(4).setHeaderValue("회사명"); selectKey = "COMPANYNAME"; orderString = "COMPANYNAME " + order; break;
                        case 4: cmodel.getColumn(4).setHeaderValue("핸디"); selectKey = "HAND"; orderString = "HAND " + order; break;
                        case 5: cmodel.getColumn(4).setHeaderValue("비고1"); selectKey = "NOTE1"; orderString = "NOTE1 " + order; break;
                        case 6: cmodel.getColumn(4).setHeaderValue("비고2"); selectKey = "NOTE2"; orderString = "NOTE2 " + order; break;
                        case 7: cmodel.getColumn(4).setHeaderValue("비고3"); selectKey = "NOTE3"; orderString = "NOTE3 " + order; break;
                    }
                    searchJoinMembers(selectKey,orderString);
                    createGroups();
                    jBtnPrint.setEnabled(false);
                }
            } 
        }
    }//GEN-LAST:event_jComboOrderItemStateChanged

    private void jBtnGroupMakeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnGroupMakeActionPerformed
        // TODO add your handling code here:
        int jcomboSelectKeyIndex = jComboSelectKey.getSelectedIndex();
        int jcomboOrderIndex = jComboOrder.getSelectedIndex();
        
        if(jcomboSelectKeyIndex > 0){
            if(jcomboSelectKeyIndex > 7){
                groupMake(jcomboSelectKeyIndex, jcomboOrderIndex);
                joinMemberTable.repaint();
                groupTable.repaint();
            } else {
                 if(jcomboOrderIndex > 0){
                    groupMake(jcomboSelectKeyIndex, jcomboOrderIndex);
                    joinMemberTable.repaint();
                    groupTable.repaint();
                 } else {
                     JOptionPane.showMessageDialog(rootPane, "정렬 기준을 선택해 주세요.", "확인", WIDTH);
                     jComboOrder.requestFocus();
                 }
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "편성기준 필드를 선택해 주세요", "확인", WIDTH);
            jComboSelectKey.requestFocus();
        }
    }//GEN-LAST:event_jBtnGroupMakeActionPerformed

    private void jComboSelectKeyItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboSelectKeyItemStateChanged
        // TODO add your handling code here:
        if(evt.getStateChange() == 1){
            JComboBox jComboBox = (JComboBox)evt.getSource();
            if(jComboBox.getSelectedIndex() > 7){
                jComboOrder.removeAllItems();
                jComboOrder.addItem("선택");
                jComboOrder.setSelectedIndex(0);
                jComboOrder.setEnabled(false);
                
                if(jComboBox.getSelectedIndex() == 8){
                    //JOptionPane.showMessageDialog(rootPane, "전월성적순으로 조회", "확인", WIDTH);
                    createGroups();
                    jBtnPrint.setEnabled(false);
                }
                
                if(jComboBox.getSelectedIndex() == 9){
                    createGroups();
                    getRamdomJoinMembers();
                }
                
            } else if(jComboBox.getSelectedIndex() > 0){
                
                jComboOrder.removeAllItems();
                jComboOrder.addItem("선택");
                jComboOrder.addItem("오름차순(낮은 것부터 높은 것순)");
                jComboOrder.addItem("내림차순(높은 것부터 낮은 것순)");
                jComboOrder.setSelectedIndex(0);
                jComboOrder.setEnabled(true);
            } else {
                jComboOrder.removeAllItems();
                jComboOrder.addItem("선택");
                jComboOrder.setSelectedIndex(0);
                jComboOrder.setEnabled(true);
            }
            
        }
    }//GEN-LAST:event_jComboSelectKeyItemStateChanged

    private void jBtnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnSaveActionPerformed
        
        Golf_Manager.model.JoinMemberModel joinMemberModel =  (Golf_Manager.model.JoinMemberModel)joinMemberTable.getModel();
        Golf_Manager.model.GroupModel groupModel =  (Golf_Manager.model.GroupModel)groupTable.getModel();
        
        if(jDateGroupDate.getDate() != null){
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            String order = "";
            if(jComboSelectKey.getSelectedIndex() < 8){
                order = jComboOrder.getSelectedItem().toString();
            } 
                
//            System.out.println(sdf.format(jDateGroupDate.getDate()));
//            System.out.println(jComboSelectKey.getSelectedItem());
//            System.out.println(jComboOrder.getSelectedItem());
//            System.out.println(jChecRecordCheck.isSelected());
            
//            for(Group group : groupModel.getGroups()){
//                System.out.println(group.toString());
//            }
//            for(JoinMember joinMember : joinMemberModel.getJoinMembers()){
//                //System.out.println(joinMember.toString());
//            }
            //JoinMembers valid check 조편성이 한명이라도 되어야 저장 가능
            List<JoinMember> joinMembers = new ArrayList<>();
            
            for(JoinMember joinMember : joinMemberModel.getJoinMembers()){
                if(joinMember.getGroupRow() != -1 && joinMember.getGroupCol() != -1 && joinMember.getGroupNm() != null && !joinMember.getGroupNm().equals("")){
                    joinMembers.add(joinMember);
                }
            }
            
            if(joinMembers.size() > 0){
                if(JOptionPane.showConfirmDialog(rootPane, "저장 하시겠습니까?", "확인", JOptionPane.YES_NO_OPTION) == 0){
                    if(GroupDAO.selectGroupJoinMemberCount(sdf.format(jDateGroupDate.getDate())).equals("Y")){
                         if(JOptionPane.showConfirmDialog(rootPane, "조편성일자로 편성된조가 있습니다.\n저장시 기존 데이터가 삭제되고 신규 데이터가 저장됩니다.\n삭제 하시겠습니까?", "확인", JOptionPane.YES_NO_OPTION) == 0){
                             saveGroup(sdf.format(jDateGroupDate.getDate()), 
                                             jComboSelectKey.getSelectedItem().toString(), 
                                             order, 
                                             jChecRecordCheck.isSelected(), 
                                             groupModel.getGroups(), 
                                             joinMembers);
                         }
                    } else {
                        saveGroup(sdf.format(jDateGroupDate.getDate()), 
                                             jComboSelectKey.getSelectedItem().toString(), 
                                             order, 
                                             jChecRecordCheck.isSelected(), 
                                             groupModel.getGroups(), 
                                             joinMembers);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(rootPane, "편성된 조원이 없습니다. 조편성을 하시고 저장 하십시오.", "확인", WIDTH);
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "조편성일자를 선택하십시오", "확인", WIDTH);
        }
    }//GEN-LAST:event_jBtnSaveActionPerformed
    private void saveGroup(String gDate, String SelectKey, String order, Boolean recordCheck, List<Group> groups, List<JoinMember> joinMembers){
        //조편성이 한명이라도 있으면 저장
        if(JoinMemberDAO.saveGroupAndJoinMembers(gDate, 
                                                 SelectKey, 
                                                 order, 
                                                 recordCheck, 
                                                 groups, 
                                                 joinMembers)){
            JOptionPane.showMessageDialog(rootPane, "저장되었습니다.", "확인", WIDTH);
            saveGroupDate = gDate;
            jBtnPrint.setEnabled(true);
        } else {
            JOptionPane.showMessageDialog(rootPane, "저장중 오류가 발생하였습니다.", "확인", WIDTH);
        }
    }
    private void jBtnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnPrintActionPerformed
        
        //JOptionPane.showMessageDialog(rootPane, "출력", "확인", WIDTH);
        String printDate = saveGroupDate.substring(0, 4)+"년" + saveGroupDate.substring(5, 7)+"월" + saveGroupDate.substring(8, 10)+"일";
        PrinterJob printerJob = PrinterJob.getPrinterJob();  
        HashPrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();  

        attributes.add(new MediaPrintableArea(6, 6, 198, 278, MediaPrintableArea.MM)); // A4: 210x297mm  
        attributes.add(Sides.DUPLEX);  
        attributes.add(OrientationRequested.LANDSCAPE);  
//        
//        
        new PrintPreview(
            groupTable.getPrintable(JTable.PrintMode.FIT_WIDTH, new MessageFormat(printDate + " 조편성"), new MessageFormat("Page {0}") ),   
            printerJob.getPageFormat(attributes)
        );  
    }//GEN-LAST:event_jBtnPrintActionPerformed
    
    //조편성대상 조회
    private void  searchJoinMembers(String selectKey, String orderString){
        Golf_Manager.model.JoinMemberModel joinMemberModel =  (Golf_Manager.model.JoinMemberModel)joinMemberTable.getModel();
        joinMemberModel.setCheckRow(-1);
        joinMemberModel.setCheckValue(false);
        joinMemberModel.setJoinMembers(JoinMemberDAO.selectJoinMember(selectKey, orderString));
        joinMemberTable.repaint();
        searchResult.setText(joinMemberModel.getRowCount() + " 명");
        if(joinMemberModel.getRowCount() == 0){
            JOptionPane.showMessageDialog(rootPane, "조편성에 참여중인 대상자가 없습니다.", "확인", WIDTH);
        }
    }
    
    private void  createGroups(){
        Golf_Manager.model.JoinMemberModel joinMemberModel =  (Golf_Manager.model.JoinMemberModel)joinMemberTable.getModel();
        Golf_Manager.model.GroupModel groupModel =  (Golf_Manager.model.GroupModel)groupTable.getModel();
        List<Golf_Manager.vo.Group> groups = new ArrayList<>();
        final int groupMemberCnt = 4;
        
        int oneGroupCnt = 0;
        int twoGroupCnt = 0;
        int threeGroupCnt = 0;
        int fourGroupCnt = 0;
        
        int joinMemberCnt = joinMemberModel.getRowCount();
        
        if(joinMemberCnt > 0){
            if (joinMemberCnt < (groupMemberCnt + 2)){
                switch(joinMemberCnt){
                    case 5: {
                        groups.add(new Group(0, "1조", 3));
                        groups.add(new Group(0, "1조", 2));
                        break;
                    } 
                    default: {
                        groups.add(new Group(0, "1조", joinMemberCnt));
                        break;
                    }
                }
            } else {
                int quotient = (joinMemberCnt/groupMemberCnt);
                int remainder = (joinMemberCnt%groupMemberCnt);

                switch(remainder) {
                    case 0 : fourGroupCnt = quotient; break;
                    case 1 : {
                        fourGroupCnt = (quotient - 2);
                        threeGroupCnt = ((remainder + (groupMemberCnt * 2))/3);
                        break;
                    }   
                    case 2 : {
                        fourGroupCnt = (quotient - 1);
                        threeGroupCnt = ((remainder + (groupMemberCnt * 1))/3);
                        break;
                    } 
                    case 3 : {
                        fourGroupCnt = quotient;
                        threeGroupCnt = (remainder/3);
                        break;
                    }
                }
                //System.out.println("quotient : " + quotient + " remainder : " + remainder);
                //System.out.println("fourGroupCnt : " + fourGroupCnt + " threeGroupCnt : " + threeGroupCnt);
                for(int i=0; i < fourGroupCnt; i++){
                    groups.add(new Group(i, (i+1) + "조", 4));
                }

                for(int i=0; i < threeGroupCnt; i++){
                    groups.add(new Group(((groups.size()-1)+1) , (groups.size()+1) + "조", 3));
                }
            }
        }
        
        groupModel.setGroups(groups);
        groupTable.repaint();
    }
    
    //조편성
    private void groupMake(int jcomboSelectKeyIndex, int jcomboOrderIndex){
        
//      System.out.println(jcomboSelectKeyIndex);
//      System.out.println(jcomboOrderIndex);
//      System.out.println(jChecRecordCheck.isSelected());
        
        if(jcomboSelectKeyIndex > 0 && jcomboSelectKeyIndex < 8){
            if(jChecRecordCheck.isSelected()){
                //최근전적반영
                makrOrderByRecord();
                return;
            } else {
                //최근전적미반영
                makrGroupbyOrder();
            }
        } else if(jcomboSelectKeyIndex == 8) {
            if(jChecRecordCheck.isSelected()){
                //최근전적반영
                makrOrderByRecord();
                return;
            } else {
               JOptionPane.showMessageDialog(rootPane, "죄송합니다. 전월성적순은 아직 지원되지않는 기능입니다.", "확인", WIDTH);
                 return;
            }
        } else if(jcomboSelectKeyIndex == 9) {
            if(jChecRecordCheck.isSelected()){
                //최근전적반영
                makrOrderByRecord();
                return;
            } else {
               //최근전적미반영
                makrGroupbyOrder(); 
            }
        } 
        
        joinMemberTable.repaint();
        JOptionPane.showMessageDialog(rootPane, "조편성 완료!", "확인", WIDTH);
        
    }
    
    private void makrOrderByRecord () {
        JOptionPane.showMessageDialog(rootPane, "죄송합니다. 최근전적반영은 아직 지원되지않는 기능입니다.", "확인", WIDTH);
//        Golf_Manager.model.JoinMemberModel joinMemberModel =  (Golf_Manager.model.JoinMemberModel)joinMemberTable.getModel();
//        List<Golf_Manager.vo.JoinMember> joinMembers = joinMemberModel.getJoinMembers();
//        
//        int originIndex = 0;
//        while(true){
//            System.out.println(GroupDAO.getCompJoinMembrs(joinMembers.get(originIndex).getMemberSeq(), joinMembers.get(originIndex).getMemberSeq()));
//            System.out.println(GroupDAO.getCompJoinMembrs(joinMembers.get(originIndex).getMemberSeq(), joinMembers.get(originIndex).getMemberSeq()));
//            String originSeq = joinMembers.get(originIndex).getMemberSeq();
//           
//            for(JoinMember joinMember : joinMembers){
//                if(!originSeq.equals(joinMember.getMemberSeq())){
//                    //비교
//                    System.out.println(GroupDAO.getCompJoinMembrs(originSeq, joinMember.getMemberSeq()));
//                }
//            }
//            joinMembers.remove(originIndex);
//            
//            if(joinMembers.size() == 0){
//                break;
//            }
//            
//            originIndex++;
//            if(originIndex == joinMembers.size()){
//                originIndex = 0;
//            }
//        }        
    }
    private void makrGroupbyOrder () {
        Golf_Manager.model.JoinMemberModel joinMemberModel =  (Golf_Manager.model.JoinMemberModel)joinMemberTable.getModel();
        Golf_Manager.model.GroupModel groupModel =  (Golf_Manager.model.GroupModel)groupTable.getModel();
        
        List<Golf_Manager.vo.JoinMember> joinMembers = joinMemberModel.getJoinMembers();
        List<Golf_Manager.vo.Group> groups = groupModel.getGroups();
        
        for(int joinMembersRow = 0; joinMembersRow < joinMembers.size(); joinMembersRow++){
            JoinMember joinMember = joinMembers.get(joinMembersRow);
            if(joinMember.getGroupRow() == -1 && joinMember.getGroupCol() == -1 && (joinMember.getGroupNm() == null || joinMember.getGroupNm().equals(""))){
                //조배정이 없는 대상자인경우
                for(int groupRow = 0; groupRow < groups.size(); groupRow++){
                       Group group = groups.get(groupRow);
                        if(group.getGroupMemberCnt() > 0 && group.getMemberRow1() == -1 && (group.getMemberDesc1() == null || group.getMemberDesc1().equals(""))) {
                           //첫 조가 비어있는 경우 설정
                           joinMemberModel.setGroupData(joinMembersRow, group.getGroupName(), groupRow, 1);
                           groupModel.setGroupMember(groupRow, 1, joinMembersRow, joinMember.getMemberSeq(), joinMember.getName() + "(" + joinMember.getBirth() + ")");
                           break; 
                       } else if(group.getGroupMemberCnt() > 1 && group.getMemberRow2() == -1 && (group.getMemberDesc2() == null || group.getMemberDesc2().equals(""))) {
                           //두번째 조가 비어있는 경우 설정
                           joinMemberModel.setGroupData(joinMembersRow, group.getGroupName(), groupRow, 2);
                           groupModel.setGroupMember(groupRow, 2, joinMembersRow, joinMember.getMemberSeq(), joinMember.getName() + "(" + joinMember.getBirth() + ")");
                           break;
                       } else if(group.getGroupMemberCnt() > 2 && group.getMemberRow3() == -1 && (group.getMemberDesc3() == null || group.getMemberDesc3().equals(""))) {
                           //세번째 조가 비어있는 경우 설정
                           joinMemberModel.setGroupData(joinMembersRow, group.getGroupName(), groupRow, 3);
                           groupModel.setGroupMember(groupRow, 3, joinMembersRow, joinMember.getMemberSeq(), joinMember.getName() + "(" + joinMember.getBirth() + ")");
                           break;
                       } else if(group.getGroupMemberCnt() > 3 && group.getMemberRow4() == -1 && (group.getMemberDesc4() == null || group.getMemberDesc4().equals(""))) {
                           //네번째 조가 비어있는 경우 설정
                           joinMemberModel.setGroupData(joinMembersRow, group.getGroupName(), groupRow, 4);
                           groupModel.setGroupMember(groupRow, 4, joinMembersRow, joinMember.getMemberSeq(), joinMember.getName() + "(" + joinMember.getBirth() + ")");
                           break;
                       }
                }
            }
        }
    }
    
    private void getRamdomJoinMembers(){
                    
        List<JoinMember> JoinMembers = JoinMemberDAO.selectJoinMember("", "");
        if(JoinMembers.size() > 0){
            List<Integer> randomindexList = Util.getRandomRange(0, JoinMembers.size());
            if(randomindexList.size() > 0){
                List<JoinMember> newJoinMembers = new ArrayList<>();
                for(int index : randomindexList){
                    newJoinMembers.add(JoinMembers.get(index));
                }
                Golf_Manager.model.JoinMemberModel joinMemberModel =  (Golf_Manager.model.JoinMemberModel)joinMemberTable.getModel();
                joinMemberModel.setJoinMembers(newJoinMembers);
                joinMemberTable.repaint();
                searchResult.setText(joinMemberModel.getRowCount() + " 명");
            }

            jBtnPrint.setEnabled(false);
        } else {
            JOptionPane.showMessageDialog(rootPane, "조편성에 참여중인 대상자가 없습니다.", "확인", WIDTH);
        }
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable groupTable;
    private javax.swing.JButton jBtnAdd;
    private javax.swing.JButton jBtnDel;
    private javax.swing.JButton jBtnGroupMake;
    private javax.swing.JButton jBtnPrint;
    private javax.swing.JButton jBtnSave;
    private javax.swing.JCheckBox jChecRecordCheck;
    private javax.swing.JComboBox jComboOrder;
    private javax.swing.JComboBox jComboSelectKey;
    private com.toedter.calendar.JDateChooser jDateGroupDate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTable joinMemberTable;
    private javax.swing.JLabel searchResult;
    // End of variables declaration//GEN-END:variables
    private String saveGroupDate;
}
